import {Injectable} from '@angular/core';
import {Camera, CameraOptions} from "@ionic-native/camera";
import {Platform} from "ionic-angular";
import {WechatJsSdkProvider} from "@providers/wechat-js-sdk";
import {ImagePickerObject} from "@common/ImagePickerObject";
import {Util} from "@providers/util";
import {DialogProvider} from "@providers/dialog";

/*
  Generated class for the NativeCameraProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class NativeCameraProvider {

  constructor(private camera: Camera,
              private platform: Platform,
              private dialog: DialogProvider,
              private wechat: WechatJsSdkProvider) {
  }

  openCamera(): Promise<ImagePickerObject> {
    return new Promise<ImagePickerObject>((resolve, reject) => {
        if (this.platform.is("cordova")) {
          let options: CameraOptions = {
            quality: 25,
            destinationType: this.camera.DestinationType.DATA_URL,
            encodingType: this.camera.EncodingType.JPEG,
            mediaType: this.camera.MediaType.PICTURE
          };
          this.camera.getPicture(options).then((imageData) => {
            let base64Image = 'data:image/jpeg;base64,' + imageData;
            resolve({base64: base64Image, type: "cordova", url: base64Image})
          }, (err) => {
            this.dialog.showAlert(err);
          });
        } else if (this.wechat.isWechat()) {
          this.wechat.chooseImage({
            sizeType: ['original', 'compressed'],
            sourceType: ['camera'],
          }).then((res) => {
            res = res['localIds'];
            if (Util.isNull(res)) return;
            if (res.length == 0) {
              return;
            }
            let localId = res[0];
            this.wechat.getLocalImgData(localId)
              .then(localData => {
                resolve({type: 'Wechat', base64: localData, url: localData});
              });
          });
        } else {
          let input = document.createElement("input");
          input.setAttribute('type', 'file');
          input.setAttribute('accept', 'image/*');
          input.setAttribute('capture', 'camera');
          input.addEventListener('change', (e) => {
            let files = input.files;
            let file = files[0];
            if (Util.isNull(files)) return;
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function () {
              let base64 = this.result;
              resolve({type: 'h5', base64: base64, url: base64});
            }
          });
          input.click();
        }
      }
    )
  }

}
